/**
 * 获取路径信息
 * @param {string} key 指定结果key, 对应的key 值参考下方keysMap
 * @param {string} url 路径
 */
export const getUrlOptions = (url: string, key: string) => {
  // keys 对照表，对应下方正则中的下标
  const keysMap = new Map([
    ["search", 8],
    ["port", 5],
    ["hostname", 3],
    ["host", 4],
    ["protocol", 2],
    ["origin", 1],
  ]);
  /* eslint-disable no-useless-escape */
  const regexp = /(([^:]+:)\/\/(([^:\/\?#]+):?(\d+)?))([^?]+)?(\?([^?]*))?/;

  const match = regexp.exec(url);

  // 校验是否为真
  if (!(match && match.length)) return;

  // 返回指定结果
  if (keysMap.has(key)) {
    const index = keysMap.get(key);
    return match[index as number];
  }

  // 返回全部匹配结果
  const result: any = {};

  for (const key of keysMap.keys()) {
    const index = keysMap.get(key);

    result[key] = match[index as number];
  }

  return result;
};
